package h0907;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 最长有效括号
 * @date 2024/9/7 17:30
 */
public class LongestValidBracket {
    public static void main(String[] args) {
        String s = "(()";
        System.out.println(longestValidParentheses2(s));
    }

    public static int longestValidParentheses(String s) {
        Deque<Integer> stack = new LinkedList<>();
        stack.push(-1);
        int maxLen = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(') {
                stack.push(i);
            } else {
                stack.pop();
                if (!stack.isEmpty()) {
                    maxLen = Math.max(maxLen, i - stack.peek());
                } else {
                    //当前栈为空的情况下，push进当前i
                    stack.push(i);
                }
            }
        }
        return maxLen;
    }

    //快慢指针
    public static int longestValidParentheses2(String s) {
        int maxLen = 0;
        int left = 0;
        int right = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(') {
                left++;
            } else {
                right++;
            }
            if (left == right) {
                maxLen = Math.max(maxLen, 2 * right);
            } else if (right > left) {
                //如果右括号多了，那么重置计数器
                left = 0;
                right = 0;
            }
        }
        //清空缓存
        left = 0;
        right = 0;
        for (int j = s.length() - 1; j >= 0; j--) {
            char c = s.charAt(j);
            if (c == '(') {
                left++;
            } else {
                right++;
            }
            if (left == right) {
                maxLen = Math.max(maxLen, 2 * left);
            } else if (left > right) {
                //如果左括号多了，那么重置计数器
                left = 0;
                right = 0;
            }
        }
        return maxLen;
    }
}
